//
//  PhotoListController.m
//  MultiSelectPhoto
//
//  Created by Burn on 2019/6/18.
//  Copyright © 2019 menksoft. All rights reserved.
//

#import "PhotoListController.h"
#import <Photos/Photos.h>
#import "FaceImageCell.h"

#import "MultiSelectImageController.h"

@interface PhotoListController ()<UITableViewDelegate,UITableViewDataSource>

@property(strong,nonatomic) UITableView *tableView;


@property(strong,nonatomic) NSMutableArray *allTitleImage; //   @[@{title : @[images,PHAssetCollection,assets.count照片个数]}, @{title : @[images,PHAssetCollection,assets.count照片个数]},@{title : @[images,PHAssetCollection,assets.count照片个数]}]


@property(strong,nonatomic) NSMutableArray *allPhoto;       //  所有照片

@property(strong,nonatomic) NSMutableArray <PHAsset *>*lastAssets;
@end
static NSString *ID = @"PhotoListControllerID";
@implementation PhotoListController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    
    if (self.allTitleImage.count == 0) {
        MultiSelectImageController *vc = [[MultiSelectImageController alloc]init];
        [self.navigationController pushViewController:vc animated:NO];
        [self getThumbnailImages];

    }else{
        [self.tableView reloadData];
    }

    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(dismiss)];
    
}

- (void)dismiss{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([FaceImageCell class]) bundle:[NSBundle mainBundle]] forCellReuseIdentifier:ID];
    self.tableView.rowHeight = 60;
    [self.view addSubview:self.tableView];
    self.view.backgroundColor = [UIColor whiteColor];

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.allTitleImage.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
//     @[@{title : @[images,PHAssetCollection,assets.count照片个数]},
    
    FaceImageCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (!cell) {
        cell = [[FaceImageCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
    }
    NSString *key = [self.allTitleImage[indexPath.row] allKeys].firstObject;
    cell.imageV.image = [[self.allTitleImage[indexPath.row] valueForKey:key] firstObject];

    NSString *keyText = [NSString stringWithFormat:@"%@ (%@)",key,[[self.allTitleImage[indexPath.row] objectForKey:key] lastObject]];
    NSMutableAttributedString *aString = [[NSMutableAttributedString alloc]initWithString:keyText];
    NSRange range1 = [keyText rangeOfString:@"("];
    NSRange range2 = [keyText rangeOfString:@")"];
    NSRange range = NSMakeRange(range1.location, range2.location + range2.length - range1.location);
    [aString addAttribute:NSForegroundColorAttributeName value:[UIColor lightGrayColor] range:range];
    cell.label.attributedText = aString;
    
    return cell;
}

#pragma mark - 将图片传给
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    //  @[@{title : @[images,PHAssetCollection,assets.count照片个数]},
    NSArray *array =  [self.allTitleImage[indexPath.row] objectForKey:[[self.allTitleImage[indexPath.row] allKeys] firstObject]] ;
    PHAssetCollection *assetCollection = array[1];
    
    MultiSelectImageController *vc = [[MultiSelectImageController alloc]init];
    vc.navTitle = [[self.allTitleImage[indexPath.row] allKeys] firstObject];
    vc.assetCollection = assetCollection;
    [self.navigationController pushViewController:vc animated:YES];
    
}



/*photo 相关*/

/**
 *  获得所有相簿中的缩略图
 */
- (void)getThumbnailImages
{
//    [self.lastAssets removeAllObjects];
    
    // 获得相机胶卷 All Photos(所有照片)
    PHAssetCollection *cameraRoll = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeSmartAlbumUserLibrary options:nil].lastObject;
    [self enumerateAssetsInAssetCollection:cameraRoll original:YES];
    
    
    //  最近
    PHAssetCollection *recently = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeSmartAlbumRecentlyAdded options:nil].lastObject;
    [self enumerateAssetsInAssetCollection:recently original:YES];


    // 获得所有的自定义相簿
    PHFetchResult<PHAssetCollection *> *assetCollections = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];

    // 遍历所有的自定义相簿
    for (PHAssetCollection *assetCollection in assetCollections) {
        [self enumerateAssetsInAssetCollection:assetCollection original:NO];

    }

    //  屏幕截图
    PHAssetCollection *screenshots = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeSmartAlbumScreenshots options:nil].lastObject;
    [self enumerateAssetsInAssetCollection:screenshots original:YES];
    


}


/*
 typedef NS_ENUM(NSInteger, PHAssetCollectionType) {
 PHAssetCollectionTypeAlbum      = 1, // 在 照片 应用中创建的相簿或者通过iTunes同步的在iOS设备上显示的相簿
 PHAssetCollectionTypeSmartAlbum = 2, // 照片 应用中内置的相簿
 PHAssetCollectionTypeMoment     = 3, // 照片 应用中的 时刻
 } PHOTOS_ENUM_AVAILABLE_IOS_TVOS(8_0, 10_0);
 */


/*
 typedef NS_ENUM(NSInteger, PHAssetCollectionSubtype) {
 // PHAssetCollectionTypeAlbum regular subtypes
 PHAssetCollectionSubtypeAlbumRegular         = 2, // 在 相册 应用中创建的相簿
 PHAssetCollectionSubtypeAlbumSyncedEvent     = 3, // 从iPhone中同步到设备的 事件
 PHAssetCollectionSubtypeAlbumSyncedFaces     = 4, // 从iPhone中同步到设备的 面孔（人物）
 PHAssetCollectionSubtypeAlbumSyncedAlbum     = 5, // 从iPhone中同步到设备的相簿
 PHAssetCollectionSubtypeAlbumImported        = 6, // 从相机或者外部存储设备中导入的相簿
 // PHAssetCollectionTypeAlbum shared subtypes
 PHAssetCollectionSubtypeAlbumMyPhotoStream   = 100, // 用户自己的iCloud照片流
 PHAssetCollectionSubtypeAlbumCloudShared     = 101, // 一个iCloud共享照片流
 // PHAssetCollectionTypeSmartAlbum subtypes
 PHAssetCollectionSubtypeSmartAlbumGeneric    = 200, // 没有指定子类型的智能相簿
 PHAssetCollectionSubtypeSmartAlbumPanoramas  = 201, // 包含了照片库中所有全景照片的智能相簿——全景照片
 PHAssetCollectionSubtypeSmartAlbumVideos     = 202, // 包含了照片库中所有视频的智能相簿——视频
 PHAssetCollectionSubtypeSmartAlbumFavorites  = 203, // 包含了照片库中所有用户标记为喜欢的资源的智能相簿——个人收藏
 PHAssetCollectionSubtypeSmartAlbumTimelapses = 204, // 包含了照片库中所有延时视频的智能相簿——慢动作
 PHAssetCollectionSubtypeSmartAlbumAllHidden  = 205, // 包含了 照片 应用中所有从 时刻 中隐藏的资源的智能相簿——
 PHAssetCollectionSubtypeSmartAlbumRecentlyAdded = 206, // 包含了所有最近添加到图片库的资源的智能相簿——
 PHAssetCollectionSubtypeSmartAlbumBursts     = 207, // 包含了所有连拍的智能相簿——连拍快照
 PHAssetCollectionSubtypeSmartAlbumSlomoVideos = 208, // 包含了 照片 应用中所有慢动作视频的智能相簿——慢动作
 PHAssetCollectionSubtypeSmartAlbumUserLibrary = 209, // 包含了所有用户自己的图库的资源的智能相簿（而不是来自于iCloud共享流的资源）
 PHAssetCollectionSubtypeSmartAlbumSelfPortraits PHOTOS_AVAILABLE_IOS_TVOS(9_0, 10_0) = 210, // 包含了所有使用前置摄像头拍摄的资源的智能相册——自拍
 PHAssetCollectionSubtypeSmartAlbumScreenshots PHOTOS_AVAILABLE_IOS_TVOS(9_0, 10_0) = 211, // 包含了所有使用屏幕截图的资源的智能相册——屏幕快照
 PHAssetCollectionSubtypeSmartAlbumDepthEffect PHOTOS_AVAILABLE_IOS_TVOS(10_2, 10_1) = 212, // 包含了所有兼容设备上使用景深效果拍摄的资源的智能相册
 PHAssetCollectionSubtypeSmartAlbumLivePhotos PHOTOS_AVAILABLE_IOS_TVOS(10_3, 10_2) = 213, // 包含了所有Live Photo的智能相册——Live Photo
 // Used for fetching, if you don't care about the exact subtype
 PHAssetCollectionSubtypeAny = NSIntegerMax // 所有可能的子类型
 } PHOTOS_ENUM_AVAILABLE_IOS_TVOS(8_0, 10_0);

 */




/**
 *  遍历相簿中的所有图片
 *
 *  @param assetCollection 相簿
 *  @param original        是否要原图
 */
- (void)enumerateAssetsInAssetCollection:(PHAssetCollection *)assetCollection original:(BOOL)original
{
    
    //https://www.jianshu.com/p/78960c4fd99d
    /*
     typedef NS_ENUM(NSInteger, PHImageRequestOptionsVersion) {
     PHImageRequestOptionsVersionCurrent = 0, // 图片的最新版本（包括所有编辑版本）
     PHImageRequestOptionsVersionUnadjusted, // 原版，无任何调整编辑
     PHImageRequestOptionsVersionOriginal // 原始的高保真的版本
     } PHOTOS_ENUM_
     */
    
    /*
     typedef NS_ENUM(NSInteger, PHImageRequestOptionsDeliveryMode) {
     PHImageRequestOptionsDeliveryModeOpportunistic = 0, // 为了平衡图像质量和响应速度，Photos会提供一个或多个结果
     PHImageRequestOptionsDeliveryModeHighQualityFormat = 1, // 只提供最高质量的图像，无论它需要多少时间加载
     PHImageRequestOptionsDeliveryModeFastFormat = 2 // 最快速的得到一个图像结果，可能会牺牲图像质量。
     } PHOTOS_ENUM_AVAILABLE_IOS_TVOS(8_0, 10_0);
     */
    
    /*
     PHImageRequestOptionsResizeMode
     typedef NS_ENUM(NSInteger, PHImageRequestOptionsResizeMode) {
     PHImageRequestOptionsResizeModeNone = 0, // 不做任何调整
     PHImageRequestOptionsResizeModeFast, // 最快速的调整图像大小，有可能比给定大小略大
     PHImageRequestOptionsResizeModeExact, // 保证与给定大小相等。如果使用normalizedCropRect属性，则必须指定为该模式。
     } PHOTOS_ENUM_AVAILABLE_IOS_TVOS(8_0, 10_0);
     */
    
    NSString *key = @"";
    //  获取相册名称PHAssetCollectionSubtypeAlbumRegular
    switch (assetCollection.assetCollectionSubtype) {
        case PHAssetCollectionSubtypeAlbumRegular:
            key = assetCollection.localizedTitle;
            break;
        case PHAssetCollectionSubtypeSmartAlbumUserLibrary:
            key = @"所有照片";
            break;
        case PHAssetCollectionSubtypeSmartAlbumRecentlyAdded:
            key = @"最近添加";
            break;
        case PHAssetCollectionSubtypeSmartAlbumScreenshots:
            key = @"屏幕快照";
            break;


        default:
            break;
    }
    
    
    
    PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
    // 同步获得图片, YES 为同步 , NO不一定异步
    options.synchronous = NO;
    options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
    
    // 获得某个相簿中的所有PHAsset对象
    PHFetchResult *assets = [PHAsset fetchAssetsInAssetCollection:assetCollection options:nil];
    PHAsset *asset = assets.firstObject;
        // 是否要原图
        CGSize size = original ? CGSizeMake(asset.pixelWidth, asset.pixelHeight) : CGSizeZero;

        
        // 从asset中获得图片
        [[PHImageManager defaultManager] requestImageForAsset:asset targetSize:size contentMode:PHImageContentModeDefault options:options resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
            
            if (result) {
                NSArray *arr = [[NSArray alloc]initWithObjects:result,assetCollection,@(assets.count), nil];
//                [self.allTitleImage addObject:@{key : arr}];
                [self.allTitleImage insertObject:@{key : arr} atIndex:0];
                [self.tableView reloadData];
            }
        }];

}



- (NSMutableArray *)allTitleImage{
    if (!_allTitleImage) {
        _allTitleImage = [NSMutableArray array];
    }
    return _allTitleImage;
}

- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return _tableView;
}

- (NSMutableArray *)allPhoto{
    if (!_allPhoto) {
        _allPhoto = [NSMutableArray array];
    }
    return _allPhoto;
}

- (NSMutableArray <PHAsset *>*)lastAssets{
    if (!_lastAssets) {
        _lastAssets = [NSMutableArray array];
    }
    return _lastAssets;
}


@end
